<template>
  <div>
    <div>
      <router-view></router-view>
    </div>
    <div class="tabbar">
      <div class="tabbar-item" :class="{active: activeIndex === index}" v-for="(item, index) in tabbarData" :key="index" @click="toggleTabbar(index, item.name)">{{item.title}}</div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'Main',
    data() {
      return {
        activeIndex: 0,
        tabbarData: [
          {title: '首页', name: 'Index'},
          {title: '分类', name: 'Yi'},
          {title: '购物车', name: 'Shopping'},
          {title: '我的', name: 'My'}
        ]
      };
    },
    
    created() {
      console.log('this.$route ==> ', this.$route);

      //纠正路由
      //获取路由名称
      let routeName = this.$route.name;
      let currentIndex = -1;
      //查找当前激活的路由
      for (let i = 0; i < this.tabbarData.length; i++) {
        if (routeName === this.tabbarData[i].name) {
          currentIndex = i;
          break;
        }
      }

      if (this.activeIndex !== currentIndex) {
        this.activeIndex = currentIndex;
      }
    },
    methods: {
      toggleTabbar(index, name) {
        if (this.activeIndex === index) {
          console.log('已经处于激活状态');
          return;
        }
        this.activeIndex = index;
        this.$router.push({name});
      }
    }
  }
</script>

<style lang="less" scoped>
.tabbar{
  position: fixed;
  height: 50px;
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
  left: 0;
  bottom: 0;
  right: 0;
  display: flex;
}
.tabbar-item{
  flex: 1;
  text-align: center;
  line-height: 50px;
}
.tabbar-item.active{
  background-color: #e4393c;
  color: #fff;
}
</style>